package com.wall.haven.exception;

import com.wall.haven.enums.ResultCode;

/**
 * 服务异常封装
 *
 * @author ChenWangKun
 * @since 2023-05-06
 */
public class ServiceException extends RuntimeException {

    private static final long serialVersionUID = -4013655514127118337L;
    /**
     * 错误码
     */
    private long code;

    public ServiceException(Integer code, String message) {
        super(message);
        this.code = code;
    }

    public ServiceException(String message, Throwable e) {
        super(message, e);
        if (e instanceof ServiceException) {
            this.code = ((ServiceException) e).code;
        }
    }

    public ServiceException(Integer code, String message, Throwable e) {
        super(message, e);
        this.code = code;
    }

    public ServiceException(String message, Object... args) {
        super(String.format(message, args));
        if (args != null && args.length > 0 && args[args.length - 1] instanceof Throwable) {
            Throwable ex = (Throwable) args[args.length - 1];
            this.initCause(ex);
            if (ex instanceof ServiceException) {
                this.code = ((ServiceException) ex).code;
            }
        }
    }

    /**
     * 异常构造
     *
     * @param message
     */
    public ServiceException(String message) {
        super(message);
        this.code = ResultCode.FAILED.code;
    }

    public ServiceException(ResultCode error){
        super(error.msg);
        this.code = error.code;
    }

    public long getCode() {
        return code;
    }

    public void setCode(long code) {
        this.code = code;
    }
}